package com.lv.controller;

import com.lv.data.Result;
import com.lv.enums.ResultEnum;
import com.lv.exception.LongExcep;
import com.lv.pojo.TbSeller;
import com.lv.service.SellerService;
import com.lv.util.ShiroUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.security.auth.login.LoginException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("seller")
public class SellerController {
    @DubboReference
    private SellerService ss;

    @RequestMapping("register")
    @ResponseBody
    public Result register(TbSeller s){

            TbSeller seller = ss.selectById(s.getSellerId());
            //是否已经注册
            if(seller!= null){
                return Result.response(ResultEnum.REGISTER_ALREADY);
            }
            //登陆名不可为空
            if (s.getSellerId() == null && s.getSellerId().equals("")){
                return Result.response(ResultEnum.REGISTER_NULL);
            }
            //密码不可为空
            if (s.getPassword() == null && s.getPassword().equals("")){
                return Result.response(ResultEnum.REGISTER_PWD_NULL);
            }
            String pwd =s.getPassword();
            String salt = "610404";
            s.setPassword(ShiroUtils.encryptPassword("MD5", pwd, salt));
            ss.add(s);
            return Result.OK();


    }
    //登录
    @RequestMapping("login")
    @ResponseBody
    public Map login(String sellerId,String password) {
        Map map = new HashMap();
        //创建subject对象
        Subject subject = SecurityUtils.getSubject();
        //将表单提交的 账号和密码 封装成shiro的 token
        UsernamePasswordToken token = new UsernamePasswordToken(sellerId, password);
        //执行登录逻辑
        try {
            subject.login(token);
            map.put("code",1);
            map.put("message","成功");
            return map;
        } catch (UnknownAccountException ae) {
            map.put("code",2);
            map.put("message","账号不存在");
            return map;
        } catch (IncorrectCredentialsException ice) {
            map.put("code",3);
            map.put("message","密码错误");
            return map;

        } catch (LongExcep e){
            map.put("code",4);
            map.put("message","未审核");
            return map;

        }
    }
}
